<template>
	<div>		
	<!-- 面包屑导航区 -->
	<el-breadcrumb separator="/">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>权限管理</a></el-breadcrumb-item>
		  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图 -->
		<el-card>
			<!-- 添加角色按钮 -->
			<el-row>
				<el-col :span="4">
					<el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
				</el-col>
			</el-row>
			<!-- 角色列表区域 -->
		 <el-table :data="rightsList" border  :header-cell-style="{textAlign: 'center'}"  :cell-style="{ textAlign: 'center' }" style="margin-top: 20px;">
			 <!-- 角色权限展开区域 -->
			 <el-table-column label="" type="expand">		
				 <template slot-scope="scope">
					 <el-row class="see" v-for="itemA in scope.row.children" :key="itemA.id" >
						 <!-- 一级权限 -->
						 <el-col :span="5">
							 <el-tag closable  @close="removeById(scope.row,itemA.id)">
								 {{itemA.authName}}
							 </el-tag>
							 <i class="el-icon-caret-right" style="margin-left: 5px;"></i>
						 </el-col>
						 <!-- 二级权限和三级权限 -->
						 <el-col :span="19">
						 	<el-row class="see" v-for="itemB in itemA.children" :key="itemB.id" >
								<el-col :span="6">
									<el-tag type="success"  closable @close="removeById(scope.row,itemB.id)">
										 {{itemB.authName}}
									</el-tag>
									<i class="el-icon-caret-right" style="margin-left: 5px;"></i>
								</el-col>
								<el-col :span="18">
									<el-tag type="warning" v-for="itemC in itemB.children" :key="itemC.id" closable @close="removeById(scope.row,itemC.id)">
										 {{itemC.authName}}
									</el-tag>
								</el-col>
							</el-row>			 
						 </el-col>
					 </el-row>
					 <!-- 将文本结构更方便看-->
					<!-- <pre>		
						 {{scope.row}}
					 </pre> -->
				 </template>
			 </el-table-column>
			  <el-table-column label="#" type="index"></el-table-column>
			  <el-table-column label="角色名称" prop="roleName"></el-table-column>
			  <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
			  <el-table-column label="操作" prop="level">
			<template slot-scope="scope">
					<el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button size="mini" type="danger" icon="el-icon-delete" @click="userDelete(scope.row)">删除</el-button>
					<el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRoles(scope.row)">分配权限</el-button>
			</template>
			  </el-table-column>
		  </el-table>
		</el-card>
		<!-- 添加角色对话框 -->
		<el-dialog title="添加用户" :visible.sync="dialogFormVisible" @close="addDialog">
		  <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-width="80px" class="demo-ruleForm">
		    <el-form-item label="角色名称" prop="username">
		  	<el-input  v-model="addForm.username" placeholder="请输入角色名称"></el-input>
		    </el-form-item>
			<el-form-item label="角色描述" prop="describe">
			<el-input  v-model="addForm.describe" placeholder="请输入角色描述"></el-input>
			</el-form-item>
		    </el-form>
		  <div slot="footer" class="dialog-footer">
		    <el-button @click="dialogFormVisible = false">取 消</el-button>
		    <el-button type="primary" @click="addUser">确 定</el-button>
		  </div>
		</el-dialog>
		<!-- 修改角色对话框 -->
		<el-dialog title="修改用户" :visible.sync="dialogFormModify" @close="modifyDialog">
		  <el-form ref="modifyFormRef" :rules="addFormRules" :model="modifyForm" label-width="80px" class="demo-ruleForm">
			  <el-form-item label="角色名称" prop="roleName">
			  <el-input  v-model="modifyForm.roleName" placeholder="请输入角色名称"></el-input>
			  </el-form-item>
			  <el-form-item label="角色描述" prop="roleDesc">
			  <el-input  v-model="modifyForm.roleDesc" placeholder="请输入角色描述"></el-input>
			  </el-form-item>
		    </el-form>
		  <div slot="footer" class="dialog-footer">
		    <el-button @click="dialogFormModify = false">取 消</el-button>
		    <el-button type="primary" @click="modify">确 定</el-button>
		  </div>
		</el-dialog>
		<!-- 分配权限对话框 -->
		<el-dialog title="分配权限" :visible.sync="dialogshowSetRoles" @close="setRight"> 
		  <el-form label-width="80px" class="demo-ruleForm">
			<el-tree :data="howSetRoles" 
			:props="defaultProps" 
			node-key="id"
			:default-checked-keys="defaultKeys"
			show-checkbox 
			:default-expand-all="true" 
			ref="treeRef"
			></el-tree>
		    </el-form>
		  <div slot="footer" class="dialog-footer">
		    <el-button @click="dialogshowSetRoles = false">取 消</el-button>
		    <el-button type="primary" @click="allotRights">确 定</el-button>
		  </div>
		</el-dialog>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				howSetRoles:[],			//分配权限对话框 所有权限数据列表
				rightsList:[],			//所有权限列表数据
				dialogFormVisible:false,		////添加角色对话框默认显示隐藏
				dialogFormModify:false,			//修改角色对话框默认显示隐藏
				dialogshowSetRoles:false,		//分配角色对话默认显示隐藏
				addForm:{				//添加角色表单数据
					username:'',
					describe:''
				},
				defaultKeys:[],
				modifyForm:{		//修改角色对话框数据
					roleName:'',
					roleDesc:'',
					id:0
				},
				resId:0,			//分配权限上传使用的角色id
				 defaultProps: {		//树形控件属性绑定对象
				          children: 'children',			//父子节点嵌套
				          label: 'authName'			//节点展示名称
				        },
				addFormRules: {		//添加用户表单验证规则
					  username: [
						{ required: true, message: '请输入角色名称', trigger: 'blur' },
						{ min: 1, max: 10, message: '长度在 1 ~ 10 个字符', trigger: 'blur' }
					  ],
					  describe: [
					   { required: true, message: '请输入角色描述', trigger: 'blur' },
					   { min: 1, max: 20, message: '长度在 1 ~ 20 个字符', trigger: 'blur' }
					  ],
					  roleName: [
						{ required: true, message: '请输入角色名称', trigger: 'blur' },
						{ min: 1, max: 10, message: '长度在 1 ~ 10 个字符', trigger: 'blur' }
					  ],
					  roleDesc: [
					   { required: true, message: '请输入角色描述', trigger: 'blur' },
					   { min: 1, max: 20, message: '长度在 1 ~ 20 个字符', trigger: 'blur' }
					  ],
				}
			}
		},
		
		methods:{
			addDialog(){		//监听添加用户对话框的关闭时间事件
				this.$refs.addFormRef.resetFields()		//重置添加用户对话框数据
			},
			modifyDialog(){		//监听修改用户对话框的关闭时间事件
				this.$refs.modifyFormRef.resetFields()		//重置添加用户对话框数据
			},
			getRightsList(){	//获取权限列表
				this.$axios.get('roles',{params:this.queryInfo}).then(data => {
					console.log(data.data)
					this.rightsList = data.data.data
				})
			},
			addUser(){			//添加角色对话框确认事件
				this.$refs.addFormRef.validate(valid => {		//验证数据是否合法
					console.log(valid)
					if(valid == true){
						var data = {
							roleName:this.addForm.username,
							roleDesc:this.addForm.describe,
						}
						this.$axios.post('roles',data).then(src => {
							console.log(src.data)
							this.$message({message: '添加角色成功', type: 'success'});
							this.getRightsList()
						})
						this.dialogFormVisible = false
					}
				})
			},
			handleEdit(row){		//点击修改用户触发
				console.log(row)
				this.dialogFormModify = true
				this.modifyForm.roleName = row.roleName
				this.modifyForm.roleDesc = row.roleDesc
				this.modifyForm.id = row.id
			},
			modify(){		//用户确定修改事件
				this.$refs.modifyFormRef.validate(valid => {
					console.log(valid)
					if(valid == true){
						var id = this.modifyForm.id
							var data = {
								roleName:this.modifyForm.roleName,
								roleDesc:this.modifyForm.roleDesc
							}
						this.$axios.put('roles/'+id,data).then(data => {
							console.log(data.data)
							if(data.data.meta.status == 200){
								this.$message({message: '修改角色信息成功', type: 'success'});
							}else{
								this.$message({message: '修改角色信息失败', type: 'error'});
							}
								this.getRightsList()
							})
						this.dialogFormModify = false
					}
				})
			},
			userDelete(row){			//删除角色
				console.log(row)
				this.$confirm('此操作将永久删除该角色, 是否继续?', '提示',{
					confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'
				        }).then(() => {
							console.log(row.id)
							this.$axios.delete('roles/'+row.id).then(data => {
								console.log(data.data)
								this.getRightsList()
							})
				          this.$message({type: 'success',message: '删除成功!'
				          });
				        }).catch(() => {
				          this.$message({type: 'info',message: '已取消删除'
				       });          
				   });
			},
			removeById(row,id){		//根据 id 删除对应的权限
				this.$confirm('此操作将永久删除该角色, 是否继续?', '提示',{
					confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'
				        }).then(() => {
							console.log(row,id)
							this.$axios.delete('roles/'+row.id+'/rights/'+id).then(data => {
								console.log(data.data)
								row.children = data.data.data		//重新赋值角色权限 防止页面刷新
								// this.getRightsList()
							})
				          this.$message({type: 'success',message: '删除成功!'
				          });
				        }).catch(() => {
				          this.$message({type: 'info',message: '已取消删除'
				       });          
				   });
			},
			showSetRoles(role){		//展示分配权限对话框
			//获取所有权限数据列表
			console.log(role.id)
			this.resId = role.id
			this.$axios.get('rights/tree').then(data => {
				this.howSetRoles = data.data.data
				console.log(this.howSetRoles)
			})
				//递归获取三级节点
				this.getLeafKeys(role,this.defaultKeys)
				this.dialogshowSetRoles = true
			},
			//通过 递归 形式,获取角色下所有三级权限的 id,并保存到 defKeys 数组中
			getLeafKeys(node,arr){		
				if(!node.children){		//如果当前 node 节点没有 children 属性,则表示当前为三级节点
					return arr.push(node.id)		//如果为三级节点那么就向 arr 这个数组当中添加 node.id
				}
					//如果不为三级节点的话就调用递归(forEach 循环当前 node 里面的所有数组)
				node.children.forEach( item => this.getLeafKeys(item,arr))
			},
			setRight(){			//监听分配权限对话框关闭
				this.defaultKeys = []
			},
			allotRights(row){		//分配权限对话框确定事件
				const keys = [		//获取全选中和半选中的节点id值进行展开合并为一个新的数组
					...this.$refs.treeRef.getHalfCheckedKeys(),		//获取半选中
					...this.$refs.treeRef.getCheckedKeys()			//获取全选中
				]
				console.log(keys)
				const idStr = keys.join(',')
				this.$axios.post('roles/'+this.resId+'/rights',{rids:idStr}).then(data => {
					console.log(data.data)
					if(data.data.meta.status == 200){
						this.$message({message: '分配角色权限成功', type: 'success'});
					}else{
						this.$message({message: '分配角色权限失败', type: 'error'});
					}
					this.dialogshowSetRoles = false
					this.getRightsList()
					
				})
			}
		},
		created(){
			this.getRightsList()
		}
	}
</script>

<style lang="scss" scoped>
	.el-card{
		margin-top: 15px;
	}
	.see{
		border-top: 1px solid #eee;
		border-bottom: 1px solid #eee;
		display: flex;
		align-items: center;
		
	}
	.el-col{
		margin-top: 10px;
		margin-bottom: 10px;
	}
	.el-tag{
		margin-left: 6px;
	}
</style>
